package Dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import Negocio.Cotizacion;
import Negocio.ItemCotizacion;
import Negocio.Proveedor;
import Negocio.SolicitudCompra;
import Persistencia.HibernateUtil;

public class SolicitudCompraDao {
	
	private static SolicitudCompraDao instancia = null;
	private static SessionFactory sf = null;
	
	public static SolicitudCompraDao getInstancia() {
		if(instancia == null){
		sf = HibernateUtil.getSessionFactory();
			instancia = new SolicitudCompraDao();
		} 
		return instancia;
	}

	
	public List<SolicitudCompra> obtenerSolicitudes() {
			Session session = sf.openSession();
			session.beginTransaction();
			Query query = session.createQuery("from SolicitudCompra");
			List<SolicitudCompra> lista = (List<SolicitudCompra>) query.list();			
			session.flush();
			session.getTransaction().commit();
			session.close();
			return lista;
		
	}
	
	public List<SolicitudCompra> obtenerSolicitudes(Proveedor proveedor) {
		Session session = sf.openSession();
		session.beginTransaction();
		Query query = session.createQuery("from SolicitudCompra where proveedor = ?");
		query.setInteger(0, proveedor.getIdProveedor());
		List<SolicitudCompra> lista = (List<SolicitudCompra>) query.list();			
		session.flush();
		session.getTransaction().commit();
		session.close();
		return lista;
	}
	
	public void salvar(SolicitudCompra c)
	{
		Session session = null;
		try {
			
			session = sf.openSession();			
			session.beginTransaction();
			session.save(c);
			session.getTransaction().commit();
			session.flush();
			session.close();
		
		
		} catch (Exception e) {
			e.printStackTrace();
			if(session != null){
				session.getTransaction().rollback();	
				session.flush();
				session.close();
//				throw new RemoteException();
			}			
		}
 	}

	public void actualizar(SolicitudCompra c)	{
		Session session = null;
		try {
			
			session = sf.openSession();			
			session.beginTransaction();
			session.update(c);
			session.getTransaction().commit();
			session.flush();
			session.close();
		
		
		} catch (Exception e) {
			e.printStackTrace();
			if(session != null){
				session.getTransaction().rollback();	
				session.flush();
				session.close();
//				throw new RemoteException();
			}			
		}
 	}
	
	
	public SolicitudCompra obtenerSolicitudCompra(int id) {
		Session session = sf.openSession();
		session.beginTransaction();
		Query query = session.createQuery("from SolicitudCompra where id = ?");
		query.setInteger(0, id);
		SolicitudCompra lista = (SolicitudCompra) query.uniqueResult();
		session.flush();
		session.getTransaction().commit();
		session.close();
		return lista;
	}

}
